// 新增记录

const { standTables } = require("../../../../../app/tables-data");
const { letFieldNameToSameWay } = require("../../compile/mysql/_utils");
const { N, needParam, getValues } = require("../../utils");
const { getIsSqlVar } = require("./_utils");
const dayjs = require("dayjs");

/**
 * 校验code是否合法
 * @param {number} val code值
 * @param {string} key 键名
 * @param {object} map 映射对象
 */
function valideCodes(val = 0, key = "", map = {}) {
  const codes = map[key];
  if (codes && !codes.includes(Number(val))) {
    throw new Error(`${key}应为：${codes.join(", ")}，实为：${val}`);
  }
}

module.exports = {
  /**
   * 插入表格数据
   * @param {string} name 表名称
   */
  // 使用示例：insertTable(
  //   'user',
  //   [
  //     ["userName", "gender"],
  //     ["唐六", 1],
  //     ["程八", 2],
  //   ],
  // )
  // insertTable(tableName = needParam(), withKeysRows = []) {
  //   let [keys = [], ...insertRows] = withKeysRows;
  //   keys = keys.map(k => letFieldNameToSameWay(k));
  //   const defKeys = [];
  //   const defVals = [];
  //   const enumCodesMap = {};
  //   const { sqlFields } = standTables[tableName];
  //   sqlFields.forEach(it => {
  //     const { name, defaultValue, enums } = it;
  //     if (enums) enumCodesMap[name] = getValues(enums);
  //     if (!keys.includes(name) && defaultValue !== undefined) {
  //       defKeys.push(name);
  //       defVals.push(defaultValue);
  //     }
  //   });
  //   insertRows.forEach(it => it.push(...defVals));
  //   const allKeys = [...keys, ...defKeys];
  //   const keyStr = allKeys.map(it => letFieldNameToSameWay(it)).join(", ");
  //   const valStr = insertRows
  //     .map(arr => {
  //       return `(${arr
  //         .map((it, ind) => {
  //           const name = allKeys[ind];
  //           valideCodes(it, name, enumCodesMap);
  //           if (["create_time", "update_time"].includes(name)) {
  //             if (typeof it === "number") {
  //               it = dayjs(it).format("YYYY-MM-DD HH:mm:ss"); // 将时间戳转为 YYYY-MM-DD HH:mm:ss 格式进行存储
  //             }
  //           }
  //           return getIsSqlVar(it) ? it : `'${it}'`;
  //         })
  //         .join(", ")})`;
  //     })
  //     .join(`,${N}`);
  //   return `INSERT INTO ${tableName}${N}(${keyStr})${N}VALUES${N}${valStr};`;
  // },
  insertTable(tableName = needParam(), withKeysRows = []) {
    // let [keys = [], ...insertRows] = withKeysRows;
    // keys = keys.map(k => letFieldNameToSameWay(k));
    // const defKeys = [];
    // const defVals = [];
    // const enumCodesMap = {};
    // const { sqlFields } = standTables[tableName];
    // sqlFields.forEach(it => {
    //   const { name, defaultValue, enums } = it;
    //   if (enums) enumCodesMap[name] = getValues(enums);
    //   if (!keys.includes(name) && defaultValue !== undefined) {
    //     defKeys.push(name);
    //     defVals.push(defaultValue);
    //   }
    // });
    // insertRows.forEach(it => it.push(...defVals));
    // const allKeys = [...keys, ...defKeys];
    // const keyStr = allKeys.map(it => letFieldNameToSameWay(it)).join(", ");
    // const valStr = insertRows
    //   .map(arr => {
    //     return `(${arr
    //       .map((it, ind) => {
    //         const name = allKeys[ind];
    //         valideCodes(it, name, enumCodesMap);
    //         if (["create_time", "update_time"].includes(name)) {
    //           if (typeof it === "number") {
    //             it = dayjs(it).format("YYYY-MM-DD HH:mm:ss"); // 将时间戳转为 YYYY-MM-DD HH:mm:ss 格式进行存储
    //           }
    //         }
    //         return getIsSqlVar(it) ? it : `'${it}'`;
    //       })
    //       .join(", ")})`;
    //   })
    //   .join(`,${N}`);
    const insertStr = module.exports.getInsertFieldsStr(tableName, withKeysRows);
    return `INSERT INTO ${tableName}${N}${insertStr};`;
  },
  /**
   * 获取插入的sql字符串
   */
  getInsertFieldsStr(tableName = needParam(), withKeysRows = []) {
    let [keys = [], ...insertRows] = withKeysRows;
    keys = keys.map(k => letFieldNameToSameWay(k));
    const defKeys = [];
    const defVals = [];
    const enumCodesMap = {};
    const { sqlFields } = standTables[tableName];
    sqlFields.forEach(it => {
      const { name, defaultValue, enums } = it;
      if (enums) enumCodesMap[name] = getValues(enums);
      if (!keys.includes(name) && defaultValue !== undefined) {
        defKeys.push(name);
        defVals.push(defaultValue);
      }
    });
    insertRows.forEach(it => it.push(...defVals));
    const allKeys = [...keys, ...defKeys];
    const keyStr = allKeys.map(it => letFieldNameToSameWay(it)).join(", ");
    const valStr = insertRows
      .map(arr => {
        return `(${arr
          .map((it, ind) => {
            const name = allKeys[ind];
            valideCodes(it, name, enumCodesMap);
            if (["create_time", "update_time"].includes(name)) {
              if (typeof it === "number") {
                it = dayjs(it).format("YYYY-MM-DD HH:mm:ss"); // 将时间戳转为 YYYY-MM-DD HH:mm:ss 格式进行存储
              }
            }
            return getIsSqlVar(it) ? it : `'${it}'`;
          })
          .join(", ")})`;
      })
      .join(`,${N}`);
    return `(${keyStr})${N}VALUES${N}${valStr}`;
  },
};
